import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:palmf_hid/common/entities/data_base/my_database.dart';
import 'package:palmf_hid/common/services/Db.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/pages/main/patient/add_pet/add_pet_view.dart';
import 'package:palmf_hid/pages/main/patient/pet_info_data_grid_source.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'patient_state.dart';

class PatientLogic extends GetxController {
  final PatientState state = PatientState();
  final GlobalKey refresherKey = GlobalKey();
  final RefreshController refreshController =
      RefreshController(initialRefresh: true);
  final DataGridController _dataGridController = DataGridController();

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  //刷新
  Future<void> onRefresh() async {
    getLibraryList(isRefresh: true).then((value) {
      refreshController.requestRefresh();
      refreshController.refreshCompleted(resetFooterState: true);
    }).catchError((e) {
      MyLogUtil().i(e);
      refreshController.refreshFailed();
    });
  }

  // 拉取数据
  Future<void> getLibraryList({bool isRefresh = false}) async {
    MyLogUtil().i("localData");
    state.petInfoEntityList.clear();

    ///本地数据库数据
    var localData =
        await DbService.to.allPetInfoByScreen(state.petName, state.masterName);
    state.petInfoEntityList.addAll(localData);
  }

  void handleAdd() {
    showDialog(
        context: Get.context!,
        useSafeArea: true,
        barrierDismissible: true,
        builder: (ctx) {
          return AddPetPage(
            type: "add",
            petInfo: null,
          );
        }).then((value) {
      if (null != value && value) {
        state.petInfoEntityList.refresh();
      }
    });
  }

  void handleEdit({required PetInfo petInfo}) {
    showDialog(
        context: Get.context!,
        useSafeArea: true,
        barrierDismissible: true,
        builder: (ctx) {
          return AddPetPage(
            petInfo: petInfo,
            type: "edit",
          );
        }).then((value) {
      if (null != value) {
        state.petInfoEntityList.forEach((element) {
          if (element.id == petInfo.id) {
            element = value;
          }
        });
        state.petInfoEntityList.refresh();
      }
    });
  }

  PetInfoDataGridSource petInfoDataGridSource = PetInfoDataGridSource();

  DataGridController buildDataGridController() {
    _dataGridController.selectedRows.add(petInfoDataGridSource.dataGridRows[2]);
    _dataGridController.selectedRows.add(petInfoDataGridSource.dataGridRows[4]);
    _dataGridController.selectedRows.add(petInfoDataGridSource.dataGridRows[6]);
    return _dataGridController;
  }
}
